unit uMainForm;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Buttons, ObjTest, DBXJSON, NullableTypes, Rtti,
  TypInfo;

type
  TMainForm = class(TForm)
    BitBtn1: TBitBtn;
    MemoJSON: TMemo;
    BitBtn2: TBitBtn;
    MemoObject: TMemo;
    procedure BitBtn1Click(Sender: TObject);
    procedure BitBtn2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  MainForm: TMainForm;

implementation

uses JsonUtils;

{$R *.dfm}

procedure TMainForm.BitBtn1Click(Sender: TObject);
var
  Obj: TObjTest;
  ObjJson: TJSONValue;
begin
  Obj := TObjTest.Create;
  try
    Obj.NullableIntegerField := 3;
    Obj.NullableStringField := 'Test String Nullable Field';
    Obj.NullableDateField := StrToDate('19/11/1983');
    Obj.NullableDoubleField := 1235.43;
    Obj.NullableBooleanField := False;

    Obj.IntegerField := 3;
    Obj.StringField := 'Test String Field';
    Obj.DateField := StrToDate('19/11/1983');
    Obj.DoubleField := 1235.43;
    Obj.BooleanField := True;
    Obj.CharField := 'C';

    ObjJson := ObjectToJSON(Obj);
    MemoJSON.Text := ObjJson.ToString;
    BitBtn2.Enabled := True;
  finally
    Obj.Free;
  end;
end;

procedure TMainForm.BitBtn2Click(Sender: TObject);
var
  JSONObj: TJSONObject;
  Stream: TStringStream;
  Obj: TObject;

  RttiContext: TRttiContext;
  RttiType: TRttiType;
  RttiField: TRttiField;
  Value: TValue;
begin
  JSONObj := TJSONObject.Create;
  try
    Stream := TStringStream.Create(MemoJSON.Text);
    try
      JSONObj.Parse(Stream.Bytes,0);
      Obj := JSONToObject(JSONObj);

      Assert(Assigned(Obj));

      MemoObject.Clear;
      RttiType := RttiContext.GetType(Obj.ClassType);
      for RttiField in RttiType.GetFields do
      begin
        Value := RttiField.GetValue(Obj);
        MemoObject.Lines.Add(RttiField.Name+'='+Value.ToString);
      end;
    finally
      Stream.Free;
    end;
  finally
    JSONObj.Free;
  end;
end;

end.
